package io.jee.runshan.controller.admin;

import io.jee.medusa.orm.condition.Condition;
import io.jee.medusa.orm.condition.ConditionGroup;
import io.jee.medusa.vo.ResultBean;
import io.jee.runshan.domain.WeixinMenu;
import io.jee.runshan.domain.WeixinMenuContent;
import io.jee.runshan.domain.remote.weixin.WeixinMenuButton;
import io.jee.runshan.domain.remote.weixin.WeixinResponse;
import io.jee.runshan.service.IWeixinMenuContentService;
import io.jee.runshan.service.IWeixinMenuService;
import io.jee.runshan.service.remote.weixin.ISystemService;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.beans.BeansException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/admin/weixinMenu/")
public class WeixinMenuController {
	@Resource
	private IWeixinMenuService menuService;
	@Resource
	private IWeixinMenuContentService contentService;
	@Resource
	private ISystemService systemService;

	/**
	 * 获取微信菜单
	 * @author ynshun
	 * @param pid
	 * @return
	 */
	@RequestMapping(value = "ajaxWeixinMenu", produces = { "application/json" })
	public @ResponseBody ResultBean<List<WeixinMenu>> ajaxWeixinMenu() {
		List<WeixinMenu> menus = menuService.listAll("asc", "orderIndex");
		return ResultBean.result(true, "获取数据成功", menus);
	} 
	
	/**
	 * 获取微信菜单对应相应内容
	 * @Created: 2015年2月28日
	 * @Last_modified: 2015年2月28日 下午4:06:51
	 * @Last_modified_by: ynshun
	 * @Create_by: ynshun
	 * 
	 * @param mid
	 * @return
	 */
	@RequestMapping(value = "ajaxWeixinMenuContent", produces = { "application/json" })
	public @ResponseBody ResultBean<List<WeixinMenuContent>> ajaxWeixinMenuContent(Integer mid) {
		List<WeixinMenuContent> contents = contentService.list("menu.id", mid, "asc", "orderIndex");
		return ResultBean.result(true, "获取数据成功", contents);
	}
	
	/**
	 * 创建多图文消息子项
	 * @Created: 2015年3月3日
	 * @Last_modified: 2015年3月3日 上午11:52:47
	 * @Last_modified_by: ynshun
	 * @Create_by: ynshun
	 * 
	 * @param mid （菜单ID）
	 * @return
	 */
	@RequestMapping(value = "ajaxMenuContentCreate", produces = { "application/json" })
	public @ResponseBody ResultBean<Integer> ajaxMenuContentCreate(Integer mid) {
		if (mid == null || mid < 1) {
			return ResultBean.result(false, "参数错误");
		}
		WeixinMenuContent content = new WeixinMenuContent();
		WeixinMenu menu = menuService.get(mid);
		if (menu == null) {
			return ResultBean.result(false, "数据错误，请核对后再操作");
		}
		
		if (menu.getReType() != null && 3 != menu.getReType()) {
			contentService.delete("menu.id", mid);
		}
		
		menu.setReType(3);
		menu.setType("click");
		content.setMenu(menu);
		contentService.save(content);
		menuService.update(menu);
		return ResultBean.result(true, "创建菜单消息成功", content.getId());
	}
	
	/**
	 * 保存菜单回复项
	 * @Created: 2015年3月3日
	 * @Last_modified: 2015年3月3日 上午11:52:47
	 * @Last_modified_by: ynshun
	 * @Create_by: ynshun
	 * 
	 * @param content
	 * @param mid
	 * @param reType
	 * @return
	 */
	@RequestMapping(value = "ajaxMenuContentSave", produces = { "application/json" })
	public @ResponseBody ResultBean<?> ajaxMenuContentSave(WeixinMenuContent content, Integer mid, Integer reType) {
		if (mid == null || mid < 1) {
			return ResultBean.result(false, "参数错误");
		}
		WeixinMenu menu = menuService.get(mid);
		if (menu == null) {
			return ResultBean.result(false, "数据错误，请核对后再操作");
		}
		
		if (menu.getReType() != null && reType != menu.getReType()) {
			contentService.delete("menu.id", mid);
			content.setId(null);
		}
		menu.setReType(reType);
		menu.setType(reType == 0 ? "view" : "click");
		if(menu.getType() == "view"){
			menu.setUrl(content.getUrl());
		}
		menuService.update(menu);
		content.setMenu(menu);
		contentService.saveOrUpdate(content);
		return ResultBean.result(true, "操作成功", content.getId());
	}
	
	/**
	 * 删除菜单消息
	 * @Created: 2015年3月3日
	 * @Last_modified: 2015年3月3日 上午11:58:37
	 * @Last_modified_by: ynshun
	 * @Create_by: ynshun
	 * 
	 * @param id（菜单消息ID）
	 * @return
	 */
	@RequestMapping(value = "ajaxMenuContentDelete", produces = { "application/json" })
	public @ResponseBody ResultBean<?> ajaxMenuContentDelete(Integer id) {
		contentService.delete("id", id);
		return ResultBean.result(true, "删除菜单消息成功");
	}
	
	/**
	 * 修改微信菜单内容项
	 * @Created: 2015年3月3日
	 * @Last_modified: 2015年3月3日 下午12:04:26
	 * @Last_modified_by: ynshun
	 * @Create_by: ynshun
	 * 
	 * @param content
	 * @return
	 */
	@RequestMapping(value = "ajaxMenuContentUpdate", produces = { "application/json" })
	public @ResponseBody ResultBean<Integer> ajaxMenuContentUpdate(WeixinMenuContent content) {
		if (content.getId() == null || content.getId() < 1) {
			return ResultBean.result(false, "参数错误");
		}
		WeixinMenuContent oldContent = contentService.get(content.getId());
		if (oldContent == null) {
			return ResultBean.result(false, "数据错误，请核对后再操作");
		}
		oldContent.setContent(content.getContent());
		oldContent.setIntroducte(content.getIntroducte());
		oldContent.setOrderIndex(content.getOrderIndex());
		oldContent.setThumbnailUrl(content.getThumbnailUrl());
		oldContent.setTitle(content.getTitle());
		oldContent.setUrl(content.getUrl());
		contentService.update(oldContent);
		return ResultBean.result(true, "修改菜单消息成功");
	}
	
	/**
	 * 创建新菜单
	 * @Created: 2015年3月2日
	 * @Last_modified: 2015年3月2日 下午12:06:11
	 * @Last_modified_by: ynshun
	 * @Create_by: ynshun
	 * 
	 * @param menu
	 * @return
	 */
	@RequestMapping(value = "/ajaxMenuCreate", produces = { "application/json" })
	public @ResponseBody ResultBean<?> ajaxMenuCreate(WeixinMenu menu) {
		try {
			WeixinMenu parent = menuService.get(menu.getParentid());
			menu.setParent(parent);
			menu.setMenuKey(UUID.randomUUID().toString());
			menu.setType("click");
			menuService.save(menu);
		} catch (BeansException e) {
			e.printStackTrace();
			return ResultBean.result(false, e.getMessage());
		}
		return ResultBean.result(true, "操作成功");
	}
	
	/**
	 * 修改菜单
	 * @Created: 2015年3月2日
	 * @Last_modified: 2015年3月2日 下午12:06:42
	 * @Last_modified_by: ynshun
	 * @Create_by: ynshun
	 * 
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "/ajaxMenuUpdate", produces = { "application/json" })
	public @ResponseBody ResultBean<?> ajaxMenuUpdate(Integer id, Integer orderIndex, String name, Boolean enabled, Integer parentid, Integer level) {
		try {
			WeixinMenu menu = menuService.get(id);
			if (menu == null) {
				return ResultBean.result(false, "内部资源，请文明使用！");
			}
			if (parentid != null) {
				WeixinMenu parent = menuService.get(parentid);
				menu.setParent(parent);
			}
			menu.setOrderIndex(orderIndex);
			menu.setName(name);
			menu.setEnabled(enabled);
			menu.setLevel(level);
			
			/*ConditionGroup group = new ConditionGroup();
			group.and(Condition.onNumber("orderIndex").get(orderIndex));
			group.and(Condition.onNumber("parentid").eq(menu.getParentid()));
			List<WeixinMenu> list = menuService.list(group);
			for ( WeixinMenu m : list ) {
				m.setOrderIndex(m.getOrderIndex() + 1);
				menuService.update(m);
			}*/
			
			menuService.update(menu);
		} catch (BeansException e) {
			e.printStackTrace();
			return ResultBean.result(false, e.getMessage());
		}
		return ResultBean.result(true, "操作成功");
	}
	
	/**
	 * 菜单拖拽
	 * @param id
	 * @param orderIndex
	 * @param name
	 * @param enabled
	 * @param parentid
	 * @param level
	 * @return
	 */
	@RequestMapping(value = "/ajaxMenuDrop", produces = { "application/json" })
	public @ResponseBody ResultBean<?> ajaxMenuDrop(Integer id, Integer orderIndex, String name, Boolean enabled, Integer parentid, Integer level) {
		try {
			WeixinMenu menu = menuService.get(id);
			if (menu == null) {
				return ResultBean.result(false, "内部资源，请文明使用！");
			}
			if(menu.getParentid() == parentid){//同一级拖动
				/*if (parentid != null) {
					WeixinMenu parent = menuService.get(parentid);
					menu.setParent(parent);
				}*/
				ConditionGroup group = new ConditionGroup();
				group.and(Condition.onNumber("parentid").eq(menu.getParentid()));
				List<WeixinMenu> list = menuService.list(group);
				for ( WeixinMenu m : list ) {
					if(menu.getOrderIndex() < m.getOrderIndex() && orderIndex >= m.getOrderIndex()){
						m.setOrderIndex(m.getOrderIndex() - 1);
						menuService.update(m);
					}
				}
				menu.setOrderIndex(orderIndex);
				menuService.update(menu);
			}else{//不同级拖动
				//拖出，比原来大的顺序减1
				ConditionGroup group0 = new ConditionGroup();
				group0.and(Condition.onNumber("parentid").eq(menu.getParentid()));
				List<WeixinMenu> list0 = menuService.list(group0);
				for ( WeixinMenu m : list0 ) {
					if(m.getOrderIndex() > menu.getOrderIndex()){
						m.setOrderIndex(m.getOrderIndex() - 1);
						menuService.update(m);
					}
				}
				//拖进，把现有的加1，设置拖进的为1
				ConditionGroup group1 = new ConditionGroup();
				group1.and(Condition.onNumber("parentid").eq(parentid));
				List<WeixinMenu> list1 = menuService.list(group1);
				for ( WeixinMenu m : list1 ) {
					m.setOrderIndex(m.getOrderIndex() + 1);
					menuService.update(m);
				}
				menu.setLevel(level);
				menu.setOrderIndex(1);
				if (parentid != null) {
					WeixinMenu parent = menuService.get(parentid);
					menu.setParent(parent);
				}
				menuService.update(menu);
				//改变拖入的顺序
				ConditionGroup group2 = new ConditionGroup();
				group2.and(Condition.onNumber("parentid").eq(parentid));
				List<WeixinMenu> list2 = menuService.list(group2);
				for ( WeixinMenu m : list2 ) {
					if(menu.getOrderIndex() < m.getOrderIndex() && orderIndex >= m.getOrderIndex()){
						m.setOrderIndex(m.getOrderIndex() - 1);
						menuService.update(m);
					}
				}
				menu.setOrderIndex(orderIndex);
				menuService.update(menu);
			}
		} catch (BeansException e) {
			e.printStackTrace();
			return ResultBean.result(false, e.getMessage());
		}
		return ResultBean.result(true, "操作成功");
	}
	
	/**
	 * 删除菜单
	 * @Created: 2015年3月2日
	 * @Last_modified: 2015年3月2日 下午12:21:51
	 * @Last_modified_by: ynshun
	 * @Create_by: ynshun
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/ajaxMenuDelete", produces = { "application/json" })
	public @ResponseBody ResultBean<?> ajaxMenuDelete(Integer id) {
		try {
			WeixinMenu menu = menuService.get(id);
			if (menu == null) {
				return ResultBean.result(false, "内部资源，请文明使用！");
			}
			
			long count = menuService.count("parentid", id);
			if (count > 0) {
				return ResultBean.result(false, "请先删除子菜单后再删除！");
			}
			menuService.delete(menu);
		} catch (BeansException e) {
			e.printStackTrace();
			return ResultBean.result(false, e.getMessage());
		}
		return ResultBean.result(true, "操作成功");
	}
	
	
	
	/**
	 * 发布按钮
	 * @Created: 2015年2月28日
	 * @Last_modified: 2015年2月28日 下午5:58:46
	 * @Last_modified_by: ynshun
	 * @Create_by: ynshun
	 * 
	 * @return
	 */
	@RequestMapping(value = "ajaxWeixinMenuPublish", produces = { "application/json" })
	public @ResponseBody ResultBean<List<WeixinMenuContent>> ajaxWeixinMenuPublish() {
		ConditionGroup group = new ConditionGroup();
		group.and(Condition.onBool("enabled").eq(true));
		group.and(Condition.onNumber("level").gt(0));
		List<WeixinMenu> menus = menuService.list(group);
		
		List<WeixinMenuButton> buttons = new ArrayList<WeixinMenuButton>();
		for (WeixinMenu menu : menus) {
			if (menu.getLevel() == 1) {
				WeixinMenuButton parent = new WeixinMenuButton();
				parent.setKey(menu.getMenuKey());
				parent.setName(menu.getName());
				parent.setType(menu.getType());
				parent.setUrl(menu.getUrl());
				
				for (WeixinMenu child : menus) {
					if (child.getLevel() == 2 && child.getParentid() == menu.getId()) {
						WeixinMenuButton subMenu = new WeixinMenuButton();
						subMenu.setKey(child.getMenuKey());
						subMenu.setName(child.getName());
						subMenu.setType(child.getType());
						subMenu.setUrl(child.getUrl());
						parent.addSub(subMenu);
					}
				}
				buttons.add(parent);
			}
		}
		WeixinResponse response = systemService.createMenu(buttons);
		return ResultBean.result(response.success(), response.message());
	} 
}
